from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework_jwt.settings import api_settings
from rest_framework.generics import GenericAPIView

from .utils import OAuthQQ
from .models import OAuthQQUser
from .serializers import OAuthQQUserSerializer
# Create your views here.


# url(r'^qq/authorization/$', views.QQAuthURLView.as_view()),
class QQAuthURLView(APIView):
    """提供QQ登录的网址
    请求方式： GET /oauth/qq/authorization/?state=xxx
    state: 表示是从哪个界面进入登录界面的，登录后返回state对应的界面
    """

    def get(self, request):
        # 获取state
        state = request.query_params.get('state')

        # 调用封装的提供QQ登录的网址的类
        oauth = OAuthQQ(state=state)
        login_url = oauth.get_qq_login_url()
        return Response({'login_url': login_url})


# url(r'^qq/user/$', views.QQAuthUserView.as_view()),
class QQAuthUserView(GenericAPIView):
    """获取QQ登录用户的美多商城用户信息"""

    # 指定序列化器
    serializer_class = OAuthQQUserSerializer

    def get(self, request):
        """第三方登录前的校验逻辑"""
        # 获取code
        code = request.query_params.get('code')
        if not code:
            return Response({'message':'缺少code'}, status.HTTP_400_BAD_REQUEST)

        oauth = OAuthQQ()

        try:
            # 通过code,向QQ服务器获取access_token
            access_token = oauth.get_access_token(code)

            # 通过access_token，向QQ服务器获取openid
            openid = oauth.get_openid(access_token)
        except Exception as e:
            return Response({'message':'获取QQ用 户数据失败'}, status.HTTP_503_SERVICE_UNAVAILABLE)

        # 根据openid，查询该openid是否在美多商城中绑定了用户
        try:
            auth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 未绑定：手动创建绑定身份的access_token,并返回
            access_token = OAuthQQUser.generate_save_user_token(openid)
            return Response({'access_token':access_token})
        else:
            # 已绑定: 直接生成登录凭证 JWT,并返回
            # 获取绑定的user信息
            user = auth_user.user
            # 生成JWT token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            return Response({
                'token':token,
                'user_id':user.id,
                'username':user.username
            })

    def post(self, request):
        """实现第三方的登录逻辑"""

        # 创建序列化器对象并向序列化器中传入post请求体数据
        serializer = self.get_serializer(data=request.data)
        # 调用验证方法
        serializer.is_valid(raise_exception=True)
        # 保存序列化器结果
        user = serializer.save()

        # 生成已登录的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        return Response({
            'token': token,
            'user_id': user.id,
            'username': user.username
        })



